<template>
  <PageWrapper>
    <div ref="searchForm">
      <div style="border-bottom: 1px solid #eee; padding-bottom: 10px; font-size: 16px">
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </div>
      <BasicForm ref="form" @submit="handleSubmit" @reset="handleReset" @register="registerForm" />
    </div>

    <iframe
      v-if="iframeSrc"
      @load="iframeLoad"
      :src="iframeSrc"
      :style="{ width: '100%', height: `${reportPros.height}` }"
    ></iframe>
    <!-- 报表 -->
  </PageWrapper>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsReportUreportView',
  });
</script>
<script setup lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PageWrapper } from '/@/components/Page';
  import { schemasData } from '/@/utils/custom';
  import { listSet } from '/@/api/test/testData';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { useGlobSetting } from '/@/hooks/setting';
  import { reportData } from '/@/api/test/testData';
  import { useLoading } from '/@/components/Loading';

  const { t } = useI18n('report.ureportView');
  const { ctxPath } = useGlobSetting();
  let defaultValue = ref<any>();
  let iframeSrc = ref<string>();
  let searchForm = ref<any>();
  let form = ref<any>();
  const getTitle = ref({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('统计报表'),
  });
  const props = defineProps({
    viewCode: { type: String, default: '' },
    data: { type: Object, default: {} },
  });
  let reportPros = ref<any>({
    height: '', //iframe高度
    fileName: '', //文件名
    url: '', // 通用地址
    _t: '', // 显示按钮
  });
  //配置表单内容
  const schemas = ref<FormSchema[]>();
  const [registerForm, { getFieldsValue, validate, setProps, setFieldsValue }] = useForm({
    labelWidth: 90,
    showActionButtonGroup: true,
    baseColProps: { lg: 6, md: 8 },
    showAdvancedButton: true,
    compact: true,
  });
  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '加载中...',
  });

  // 获取uuid
  function generateUUID() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
    });
    return uuid;
  }
  // iframe加载完成
  function iframeLoad() {
    closeFullLoading();
  }
  // 重置
  function handleReset() {
    setFieldsValue(defaultValue.value);
  }
  // 查询
  function handleSubmit() {
    reportPros.value.height = document.documentElement.clientHeight * 0.72 + 'px';
    openFullLoading();
    let url = reportPros.value.url;
    schemas.value?.forEach((item) => {
      if (form.value.formModel[item.field] && item.component != 'RangePicker') {
        url += `&${item.field}=${form.value.formModel[item.field]}`;
      }
      if (item.component == 'RangePicker' && form.value.formModel[item.field]) {
        url += `&${item.field}_gte=${form.value.formModel[item.field][0]}&${item.field}_lte=${
          form.value.formModel[item.field][1]
        }`;
      }
    });
    for (const key in props.data) {
      url += `&${key}=${props.data[key]}`;
    }
    iframeSrc.value =
      url + `&key=${generateUUID()}&_t=${reportPros.value._t}&lay=${props.viewCode}`;
  }
  // 进入页面获取数据
  async function reloadData() {
    const res = await listSet({ viewCode: props.viewCode });
    // getTitle.value.value = res.layVoucherView.name;
    schemas.value = schemasData(res.layVoucherView.listQuery.queryCols);
    let listTabConfig = res.layVoucherView.listTabConfig;
    const res1 = await reportData({ url: listTabConfig.api });
    let defValue = res1.entity;
    reportPros.value.fileName = listTabConfig.title;
    reportPros.value.url = `${ctxPath}/ureport/preview?_u=file:${reportPros.value.fileName}.ureport.xml&_n=${getTitle.value.value}`;
    reportPros.value._t = listTabConfig.exportPremise;
    await setProps({
      schemas: schemas.value as FormSchema[],
    });
    let obj: any = {};
    for (const key in defValue) {
      if (key.indexOf('_gte') <= -1 && key.indexOf('_lte') <= -1) {
        obj[key] = defValue[key];
      }
      if (key.indexOf('_gte') > -1) {
        let arr = key.split('_');
        obj[arr[0]] = [];
        obj[arr[0]][0] = defValue[arr[0] + '_gte'];
        obj[arr[0]][1] = defValue[arr[0] + '_lte'];
      }

      if (defValue[key] instanceof Object) {
        for (const k in defValue[key]) {
          if (k.indexOf('_gte') > -1) {
            let arr = k.split('_');
            obj[key][arr[0]] = [];
            obj[key][arr[0]][0] = defValue[key][arr[0] + '_gte'];
            obj[key][arr[0]][1] = defValue[key][arr[0] + '_lte'];
            delete obj[key][arr[0] + '_gte'];
            delete obj[key][arr[0] + '_lte'];
          }
        }
      }
    }
    defaultValue.value = obj;
    await setFieldsValue(defaultValue.value);
    if (listTabConfig.immediate != '1') {
      await handleSubmit();
    }
  }
  reloadData();
</script>
